package com.dexilaonian.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dexilaonian.R;
import com.dexilaonian.bean.ConfirmBean;
import com.dexilaonian.bean.YiyangtBean;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.JsonUtil;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.widget.DateTimePickDialogUtil;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bakerj.backgrounddarkpopupwindow.BackgroundDarkPopupWindow;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class AgingConfiActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.iv_aging)
    ImageView ivAging;
    @Bind(R.id.tv_aging_title)
    TextView tvAgingTitle;
    @Bind(R.id.tv_aging_min)
    TextView tvAgingMin;
    @Bind(R.id.et_aging_name)
    TextView etAgingName;
    @Bind(R.id.et_aging_address)
    TextView etAgingAddress;
    @Bind(R.id.et_aging_change)
    TextView etAgingChange;
    @Bind(R.id.tv_total_aging)
    TextView tvTotalAging;
    @Bind(R.id.btn_ensure_aging)
    Button btnEnsureAging;
    @Bind(R.id.rl_aging)
    RelativeLayout rlaging;
    @Bind(R.id.rl_aging_service_time)
    RelativeLayout rlAgingServiceTime;
    @Bind(R.id.tv_service_time_aging)
    TextView tvServiceTimeAging;
    @Bind(R.id.base_title_service)
    TextView baseTitleService;
    @Bind(R.id.aging_service_time)
    TextView agingServiceTime;
    private ListView listview_dotor;
    private String confirm_url = Constant.base_url + "/customer/list.do";
    private List<YiyangtBean> list = new ArrayList<>();
    private BackgroundDarkPopupWindow window;
    private String cardid;
    private String orderid;
    private int customer_id;
    private String address;
    private String realName;
    private String province;
    private String city;
    private String tel;
    private int gender;
    private String productid;
    private int positon = 0;
    private TextView totalMoney;
    private String originalPrice;
    private String format;
    private String time;
    private String name;
    private String contentTime;
    private String introduce;

    @Override
    public int getLayoutID() {
        return R.layout.activity_agingconfil;
    }

    @Override
    public void initView() {
    }

    private void initGetdetail() {
        Map map = new HashMap();
        Okhttp.postString(true, confirm_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(AgingConfiActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 0) {
                        String data = object.optString("data");
                        ArrayList<ConfirmBean> confirmBeen = JsonUtil.json2beans(data, ConfirmBean.class);
                        for (int i = 0; i < confirmBeen.size(); i++) {
                            customer_id = confirmBeen.get(i).getCustomer_id();
                            address = confirmBeen.get(i).getAddress();
                            realName = confirmBeen.get(i).getRealName();
                            province = confirmBeen.get(i).getProvince();
                            city = confirmBeen.get(i).getCity();
                            tel = confirmBeen.get(i).getTel();
                            gender = confirmBeen.get(i).getGender();
                            etAgingName.setText(realName);
                            etAgingAddress.setText(province + city);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
            }
        });
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        baseTitleService.setText("确认订单");
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        String confirm2 = extras.getString("CONFIRM2");
        if (!TextUtils.isEmpty(confirm2)) {
            String realAddress = extras.getString("realAddress");
            String realName1 = extras.getString("realName");
            //productid = Integer.parseInt((extras.getString("projectid")));
            //serviceuserid = extras.getString("serviceuserid");
            customer_id = extras.getInt("customer_id");
            etAgingName.setText(realName1);
            etAgingAddress.setText(realAddress);
        } else {
            initGetdetail();
        }
        introduce = extras.getString("INTRODUCE");
        contentTime = extras.getString("ContentTime");
        name = extras.getString("NAME");
        originalPrice = extras.getString("originalPrice");
        productid = extras.getString("projectid");
        // productid = extras.getInt("projectid");
        Log.e("TTTproductid", productid+"=====");
        if (!TextUtils.isEmpty(name)) {
            tvAgingTitle.setText(name);
        }
        if (!TextUtils.isEmpty(introduce)) {
            tvAgingMin.setText(introduce);
        }
        if (!TextUtils.isEmpty(contentTime)) {
            tvServiceTimeAging.setText(contentTime + "分钟");
        }
        if (!TextUtils.isEmpty(originalPrice)) {
            tvTotalAging.setText("￥" + originalPrice);
        }
    }

    @OnClick({R.id.back, R.id.btn_ensure_aging, R.id.et_aging_change, R.id.rl_aging_service_time})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.et_aging_change:
                Log.e("TTTproductidproductid", productid + "");
                Intent intent = new Intent(AgingConfiActivity.this, ServiceActivity.class);
                Bundle bundle = new Bundle();
                intent.putExtra("CONFIRM", "CONFIRM");
                intent.putExtra("projectid",productid);
                //bundle.putInt("projectid",productid);
                intent.putExtra("CONFIRM00", "CONFIRM00");
                intent.putExtra("INTRODUCE",introduce);
                intent.putExtra("originalPrice",originalPrice);
                intent.putExtra("ContentTime",contentTime);
                intent.putExtra("NAME",name);
                startActivity(intent);
                break;
            case R.id.rl_aging_service_time:
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        AgingConfiActivity.this, time);
                dateTimePicKDialog.onCreateDialog(new DateTimePickDialogUtil.SelectDateTimeCallBack() {
                    @Override
                    public void isConfirm(String edString) {
                        SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        format = sfd.format(new Date(Long.parseLong(String.valueOf(edString))));
                        agingServiceTime.setText(format);
                    }
                });
                break;
            case R.id.btn_ensure_aging:
                String serviceTime = agingServiceTime.getText().toString().trim();
                if (TextUtils.isEmpty(serviceTime)) {
                    showToast("请选择上门时间");
                    return;
                }
               // initGetPay();

                break;
        }
    }
    private void initGetPay() {
        showProgressBar(true);
        Map<String, String> map = new HashMap<>();
        map.put("productid", productid+"");
        map.put("customerid", customer_id+"");
        map.put("quantity", 1+"");
        map.put("time", format);
        String order_url = Constant.base_url + "/product/saveOrder.do";
        Okhttp.postString(true, order_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(AgingConfiActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 0) {
                        String data = jsonObject.optString("data");
                        JSONObject object = new JSONObject(data);
                        orderid = object.optString("orderid");
                        String card = object.optString("card");
                        if ("null".equals(card)) {
                            showToast("请先申请孝心卡");
                            return;
                        }
                        JSONObject jsonObject2 = new JSONObject(card);
                        cardid = jsonObject2.optString("id");
                        String total_deposit = jsonObject2.optString("total_deposits");
                        showPopwindow_pay(total_deposit);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
                showToast(state);
            }
        });
    }
    /**
     * 显示popupWindow

     */
    private void showPopwindow_pay(String total_deposit) {
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.popwindowlayout_pay, null);
        RelativeLayout deshengka = (RelativeLayout) view.findViewById(R.id.rl_deshengka);
        RelativeLayout alipay = (RelativeLayout) view.findViewById(R.id.rl_alipay);
        RelativeLayout wechat = (RelativeLayout) view.findViewById(R.id.rl_wechat);
        final ImageView ivka = (ImageView) view.findViewById(R.id.ivka1);
        final ImageView ivAlipay = (ImageView) view.findViewById(R.id.iv_alipay2);
        final ImageView ivWechat = (ImageView) view.findViewById(R.id.iv_wechat3);
        final TextView payMoney = (TextView) view.findViewById(R.id.tv_pay);
        final TextView balance_pay = (TextView) view.findViewById(R.id.tv_balance_pay);
        totalMoney = (TextView) view.findViewById(R.id.total_money);
        balance_pay.setText("（余额：￥"+ total_deposit+"）");
        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
      //  totalMoney.setText("￥"+ num * mPrice);
        if (!TextUtils.isEmpty(originalPrice)) {
            totalMoney.setText("￥" + originalPrice);
        }
        window = new BackgroundDarkPopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                1100);
        window.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);
        window.setDarkStyle(-1);
        window.resetDarkPosition();
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);
        window.setBackgroundDrawable(getResources().getDrawable(R.color.colorpopuwindow));
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        window.showAtLocation(AgingConfiActivity.this.findViewById(R.id.rl_aging),
                Gravity.BOTTOM, 0, 0);
        deshengka.setOnClickListener(this);
        alipay.setOnClickListener(this);
        wechat.setOnClickListener(this);
        deshengka.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivka.setVisibility(View.VISIBLE);
                ivAlipay.setVisibility(View.GONE);
                ivWechat.setVisibility(View.GONE);
                positon = 0;
            }
        });
        alipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivAlipay.setVisibility(View.VISIBLE);
                ivka.setVisibility(View.GONE);
                ivWechat.setVisibility(View.GONE);
                positon = 1;
            }
        });
        wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivWechat.setVisibility(View.VISIBLE);
                ivka.setVisibility(View.GONE);
                ivAlipay.setVisibility(View.GONE);
                positon = 2;
            }
        });
        payMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (positon == 0) {
                    if (!TextUtils.isEmpty(orderid) && !TextUtils.isEmpty(cardid)) {
                        desungroupPay(orderid, cardid);
                    } else {
                        showToast("未获取到支付订单");
                    }
                } else if (positon == 1) {
                    showToast("支付宝支付功能暂时未开通");
                    positon = 0;
                } else {
                    showToast("微信支付功能暂时未开通");
                    positon = 0;
                }
                window.dismiss();
            }
        });
        //popWindow消失监听方法
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }
    private void desungroupPay(String orderid, String cardid) {
        showProgressBar(true);
        String pay_url = Constant.base_url + "/product/payByVIPCard.do";
        Map<String, String> map = new HashMap<>();
        map.put("orderid", orderid);
        map.put("cardid", cardid);
        Okhttp.postString(true, pay_url, map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                try {
                    JSONObject object = new JSONObject(response);
                    int status = Integer.parseInt(object.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(AgingConfiActivity.this, LoginActivity.class));
                        return;
                    }
                    if (status == 0) {
                        showToast("支付成功");
                        window.dismiss();
                        Intent intent = new Intent(AgingConfiActivity.this, SuccessActivity.class);
                        String real_name = etAgingName.getText().toString().trim();
                        String HouseAddress = etAgingAddress.getText().toString().trim();
                        String money = totalMoney.getText().toString().trim();
                        intent.putExtra("real_name", real_name);
                        intent.putExtra("HouseAddress", HouseAddress);
                        intent.putExtra("money", money);
                        startActivity(intent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
            }
        });

    }
}
